<?php

namespace App\Http\Service;

use App\Http\Util\Result;
use App\Model\Picture;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Foundation\Application;

trait ServicePicture{

    /**
     * 生成缩略图并存储到图片库
     * @author gaoyoulong
     * @param $fileName
     * @return Result
     */
    public static function makeThumbAndCreate($fileName){
        list($originalPrefixPath, $smallPrefixPath, $middlePrefixPath, $bigPrefixPath) = self::makeThumb($fileName);

        $data = [
            'img'=>$originalPrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'big_img'=>$bigPrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'middle_img'=>$middlePrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'small_img'=>$smallPrefixPath.DIRECTORY_SEPARATOR.$fileName,
        ];
        $res = Picture::create($data);
        if($res !== false){
            //@unlink($tempPath); //移除
            return Result::success()->setData($res->id);
        }
        else{
            return Result::failure();
        }
    }

    /**
     * @param $fileName
     * @return Result
     * czs
     */
    public static function makeThumbAndCreate2($fileName){
        $tempPrefixPath = config('config.tempPicPath');         //临时路径
        $originalPrefixPath = config('config.originalPicPath'); //原图路径 转移临时路径

        $originalPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $originalPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        $tempPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $tempPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        //移动原图
        $dir = dirname($originalPath);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        copy($tempPath, $originalPath);
        unlink($tempPath);
        return $originalPrefixPath.DIRECTORY_SEPARATOR.$fileName;
    }

    /**
     * @param $fileName
     * @return Result
     * czs
     */
    public static function makeThumbAndUpdate2($fileName,$old){
        $tempPrefixPath = config('config.tempPicPath');         //临时路径
        $originalPrefixPath = config('config.originalPicPath'); //原图路径 转移临时路径

        $originalPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $originalPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        $tempPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $tempPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        //移动原图
        $dir = dirname($originalPath);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        copy($tempPath, $originalPath);
        unlink($tempPath);
        $old = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR .$old;
        if (file_exists($old)) {
            unlink($old);
        }
        return $originalPrefixPath.DIRECTORY_SEPARATOR.$fileName;
    }

    public static function makeThumbAndUpdate($fileName,$id){
        list($originalPrefixPath, $smallPrefixPath, $middlePrefixPath, $bigPrefixPath) = self::makeThumb($fileName);

        $data = [
            'img'=>$originalPrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'big_img'=>$bigPrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'middle_img'=>$middlePrefixPath.DIRECTORY_SEPARATOR.$fileName,
            'small_img'=>$smallPrefixPath.DIRECTORY_SEPARATOR.$fileName,
        ];
        $res = Picture::where('id',$id)->update($data);
        if($res !== false){
            //@unlink($tempPath); //移除
            return Result::success()->setData($id);
        }
        else{
            return Result::failure();
        }
    }

    /**
     * 多图提交生成缩略图并创建数据库实例
     * @author gaoyoulong
     * @param $fileNames
     * @return array
     */
    public static function makeThumbsAndCreate($fileNames){
        $ids = [];
        foreach($fileNames as $fileName){
            list($originalPrefixPath, $smallPrefixPath, $middlePrefixPath, $bigPrefixPath) = self::makeThumb($fileName);
            $data = [
                'img'=>$originalPrefixPath.DIRECTORY_SEPARATOR.$fileName,
                'big_img'=>$bigPrefixPath.DIRECTORY_SEPARATOR.$fileName,
                'middle_img'=>$middlePrefixPath.DIRECTORY_SEPARATOR.$fileName,
                'small_img'=>$smallPrefixPath.DIRECTORY_SEPARATOR.$fileName,
            ];
            $res = Picture::create($data);
            if($res !== false){
                $ids[] = $res->id;
            }
        }

        return $ids;
    }

    /**
     * @author gaoyoulong
     * @param $fileName
     * @return array
     */
    protected static function makeThumb($fileName) {
        $tempPrefixPath = config('config.tempPicPath');         //临时路径
        $originalPrefixPath = config('config.originalPicPath'); //原图路径 转移临时路径
        $smallPrefixPath = config('config.smallPicPath');       //小图路径
        $middlePrefixPath = config('config.middlePicPath');     //中图路径
        $bigPrefixPath = config('config.bigPicPath');           //大图路径

        $smallSize = config('config.smallPicSize');         //小图大小配置
        $middleSize = config('config.middlePicSize');       //中图大小配置
        $bigSize = config('config.bigPicSize');             //大图大小配置
        //生成小图
        Picture::makeThumbPic($fileName, $tempPrefixPath, $smallPrefixPath, $smallSize);
        //生成中图
        Picture::makeThumbPic($fileName, $tempPrefixPath, $middlePrefixPath, $middleSize);
        //生成大图
        Picture::makeThumbPic($fileName, $tempPrefixPath, $bigPrefixPath, $bigSize);

        $originalPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $originalPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        $tempPath = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $tempPrefixPath . DIRECTORY_SEPARATOR . $fileName;
        //移动原图
        $dir = dirname($originalPath);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        copy($tempPath, $originalPath);
        return array($originalPrefixPath, $smallPrefixPath, $middlePrefixPath, $bigPrefixPath);
    }

    /**
     * 取固定ids的相册
     * @author gaoyoulong
     * @param $ids
     * @return mixed
     */
    public static function getListByIds($ids){
        return Picture::whereIn('id',$ids)->select('id','small_img')->get();
    }

    /**
     * 获取图片
     * @author gaoyoulong
     * @param $id
     * @return mixed
     */
    public static function getOne($id){
        return Picture::where('id',$id)->first();
    }

    /**
     * 从微信下载图片
     * czs
     */
    public static function weixinPic($mediaid) {
        $options = [
            'app_id'  => env('WECHAT_APPID', 'wxa02d075924e28b20'),
            'secret'  => env('WECHAT_SECRET', '41b4fb8812c0894fcb8b98be43bd8bc6'),
        ];
        $app = new Application($options);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken();
        $url = "https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$mediaid;
        $fileInfo = self::downloadWeixinFile($url);
        $numeric = '0123456789abcdefghijklmnopqrstuvwxyz';
        $name = substr(str_shuffle($numeric),0,8).".jpg";
        $filename = "uploads/pic/temp/".$name;
        self::saveWeixinFile($filename,$fileInfo["body"]);
        return $name;

    }

    public static function downloadWeixinFile($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER ,0);
        curl_setopt($ch, CURLOPT_NOBODY ,0);//只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header'=>$httpinfo),['body'=>$package]);
        return $imageAll;
    }

    public static function saveWeixinFile($filename,$filecontent) {
        $local_file = fopen($filename, 'w');
        if(false!==$local_file) {
            if(false!==fwrite($local_file,$filecontent)) {
                fclose($local_file);
            }
        }
    }

}


